﻿using Microsoft.EntityFrameworkCore;
using TuLing.Dto;
using TuLing.Entities;
using TuLing.IServices;

namespace TuLing.Services
{
    public class RBACUserRoleService: BaseService, IRBACUserRoleService
    {
        public RBACUserRoleService(DefaultDbContext context) : base(context) { }

        public async Task<List<long>> GetIdsAsync(long userId)
        {
            var list = await _context.UserRoles.Where(s=> s.UserId == userId).ToListAsync();
            return list.Select(s => s.RoleId).ToList();
        }

        public async Task AssignRoles(UserRoleDto input)
        {
            // clear old roles
            var old = _context.UserRoles.Where(u => u.UserId == input.UserId);
            _context.UserRoles.RemoveRange(old);

            // add new roles
            var list = new List<UserRole>();
            foreach (long id in input.RoleIds)
            {
                list.Add(new UserRole()
                {
                    UserId = input.UserId,
                    RoleId = id
                });                
            }
            _context.UserRoles.AddRange(list);
            await _context.SaveChangesAsync();
        }
        
    }
}
